#!/bin/bash
# Licensed under GPLv3
# Fritz Thomas <fritztho@gmail.com>, http://webdevappliance.com
############################

FILES="/etc/issue
/etc/libnss-mysql-root.cfg
/etc/libnss-mysql.cfg
/etc/nsswitch.conf
/etc/sudoers
/etc/bash/bashrc
/etc/screenrc
/etc/ssh/sshd_config
/etc/pam.d/samba
/etc/pam.d/system-auth
/etc/webdevappliance/base.conf
/usr/lib/webdevappliance/setup/mysql.sql
/usr/lib/webdevappliance/setup/webdevappliance.sql
/etc/apache2/includes/wda-base.conf
/etc/apache2/httpd.conf"

FILES_TARGET="/root/wda-overlay/files/wda-base"
REV=`date +%F`

#==========================================================================================#
if [[ ! -d "$FILES_TARGET" ]] ; then
	echo "'$FILES_TARGET' does not exists. Exiting"
	exit 1
fi

cd $FILES_TARGET

if [[ -z $1 ]] ; then
	echo "The first parameter has to be the version number. Exiting.";
	exit 1;
fi

TARGET="$FILES_TARGET/files-$REV"
CATEGORY=`basename $FILES_TARGET`
ARCHIVE_NAME="$CATEGORY-$1.tar.bz2"
ARCHIVE_PATH="$FILES_TARGET/$ARCHIVE_NAME"
TMPFILESDIR="files"
BACKUPFILESDIR="$FILES_TARGET/files-backup"

mkdir -p "$TARGET"

for F in $FILES
do
	if [[ -f $F ]] ; then
		echo "* Copying '$F' to '$TARGET'";
		cp -rfpu --parents "$F" "$TARGET/"
	fi
done

echo

if [[ -f "$ARCHIVE_PATH" ]] ; then
        echo "Archive ($ARCHIVE_NAME) already exists. Exiting."
        exit 1
fi


if [[ -d "$TMPFILESDIR" ]] ; then
	if [[ -d "$BACKUPFILESDIR" ]] ; then
		echo "Backup already exists. Please check the backup and remove it. Exiting."
		exit 1
	fi
	echo "* Creating Backup"
	mv "$TMPFILESDIR" "$BACKUPFILESDIR"
fi

echo "* Copying files from '$TARGET' to Temporary Directory '$TMPFILESDIR'."
cp -rfp "$TARGET" "$TMPFILESDIR"
if [[ $? -gt 0 ]] ; then
	echo "Error when copying. Exiting"
	exit 1
fi


echo "* Creating Archive '$ARCHIVE_NAME'."
tar -cjf $ARCHIVE_NAME "$TMPFILESDIR"
if [[ $? -gt 0 ]] ; then
        echo "Error when creating archive. Exiting"
        exit 1
fi


echo "* Removing temporary directory."
rm -rf "$TMPFILESDIR"

exit 0
